#include "utiladb.h"

#include <QDebug>

static QProcess *g_procSync = nullptr;
static bool g_bFinish = false;

UtilADB::UtilADB()
{
}

int UtilADB::DevicesCount(QString &text)
{
    const char *c = text.toLocal8Bit().data();

    int lineCnt = 0;
    while(*c) {
        if(*c == '\n') {
            lineCnt++;
        }
        c++;
    }
    return (lineCnt - 2);
}

void UtilADB::CallADB(const QString &args, QString &result)
{
    QString cmd = "./bin/adb.exe ";
//    QString cmd = "adb ";
    cmd = cmd + args;
    QProcess *proc = new QProcess();
//    proc->start("cmd", QStringList()<< "/c"<< cmd);
    proc->start(cmd);
    proc->waitForStarted();
    proc->waitForFinished();

    result = QString::fromLocal8Bit(proc->readAll());
}

void UtilADB::CallADBSync(const QString &args)
{
    g_bFinish = false;

    QString cmd = "./bin/adb.exe ";
//    QString cmd = "adb  ";
    cmd = cmd + args;

    g_procSync = new QProcess();
    connect(g_procSync, SIGNAL(readyReadStandardOutput()), this, SLOT(on_readOutput()));
    connect(g_procSync, SIGNAL(readyReadStandardError()), this, SLOT(on_readOutput()));
    g_procSync->setReadChannel(QProcess::StandardOutput);
//    g_procSync->start("cmd", QStringList()<< "/c"<< cmd);
    g_procSync->start(cmd);
    g_procSync->waitForStarted();

//    qDebug() << __FUNCTION__ << __LINE__;

#if 0
    while (g_bFinish == false)
    {
        g_bFinish = g_procSync->waitForFinished(500);
    }
#endif
    g_procSync->waitForFinished(-1);
    g_bFinish = true;

//    qDebug() << __FUNCTION__ << __LINE__;
}

void UtilADB::on_readOutput()
{
//    qDebug() << __FUNCTION__ << "1";
    std::string str = g_procSync->readAllStandardOutput().data();
    m_returnStr = QString::fromLocal8Bit(str.c_str());
//    qDebug() << m_returnStr;

    if(g_bFinish)
    {
//        delete g_procSync;
        g_procSync = nullptr;
    }

//    qDebug() << __FUNCTION__ << "2";
    emit(signal_adbCmdSync(m_returnStr));
}

E_ADB_RET UtilADB::PrepareADB(int *connectCnt)
{
    QString result;
    CallADB("devices", result);
    int devCnt = DevicesCount(result);
    *connectCnt = devCnt;
    if(devCnt == 0) {
        return E_ADB_NO_DEVICE;
    } else if(devCnt > 1) {
        return E_ADB_MULTI_DEVICE;
    }
    return E_ADB_OK;
}
